<template>
  <!-- 指标组件 -->
  <div class="pieChart" v-loading="loading">
    <div class="pieChart-title">
      <!-- <span>饼图</span> -->
      <span>{{ chartName }}</span>
    </div>
    <div class="pieChart-date">
      <div class="pieChart-date-div">
        <!-- 日期 -->
        <p v-if="screenTime && screenTime.length != 0">
          <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new
            Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
        </p>
        <!-- el-tooltip -->
        <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
          <el-tooltip content="筛选时段" placement="bottom" effect="light">
            <img class="right" :src="dateIcon" alt="">
          </el-tooltip>
        </p>
      </div>
      <!-- select -->
      <el-select v-if="options.length != 0" v-model="queryConditionVal" clearable placeholder="请选择"
        @change="handleChange">
        <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
    </div>
    <!-- echarts -->
    <div v-if="payloadData.data && payloadData.data.y.length != 0" :id="'pieCharts' + id" class="pieChart-echarts"
      style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import * as echarts from 'echarts';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  merchantReportQueryData,
  merchantReportQueryCondition
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
export default {
  name: 'PieChart',
  components: {},
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    },
    chartName: {
      type: String,
      default: () => {
        return '';
      }
    }
  },
  inject: ['actId'],
  data() {
    return {
      loading: false,
      dateIcon,
      emptyImg,
      data: {},
      payloadData: {},
      relativelyTimeDeal: null,
      queryConditionVal: '',
      queryConditionKey: '',
      options: []
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.merchantReportQueryDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
      },
      deep: true
    }
  },
  mounted() {
    this.merchantReportQueryConditionApi();
  },
  methods: {
    handleChange(val) {
      this.merchantReportQueryDataApi();
    },
    // 获取条件切换接口
    async merchantReportQueryConditionApi() {
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let res = await merchantReportQueryCondition({
        startTime,
        endTime,
        chartType: 3,
        toIndex: 10,
        beanName: this.id,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      })
      if (res.code === 200) {
        if (res.payload.length != 0) {
          this.options = res.payload[0].options || [];
          this.queryConditionVal = this.options[0].value || '';
          this.queryConditionKey = res.payload[0].key || '';
        }
        this.merchantReportQueryDataApi();
      }
    },
    // 获取报表数据
    async merchantReportQueryDataApi() {
      this.loading = true;
      // screenTime为菜单筛选时间
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let paramStr = {
        startTime,
        endTime,
        chartType: 3,
        toIndex: 10,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      }
      paramStr[this.queryConditionKey] = this.queryConditionVal;
      const obj=store.state.user.queryConditionObj
      store.commit('SETQUERYCONDITIONOBJ', {...obj,[`${this.id}Key`]:this.queryConditionVal})
      paramStr = JSON.stringify(paramStr);
      let res = await merchantReportQueryData({
        beanName: this.id,
        param: paramStr
      })
      if (res.code === 200) {
        this.payloadData = res.payload;
        this.capsulationDealData(0)
      }
      this.loading = false;
    },
    capsulationDealData(currentIndex) {
      this.multipleData = [];
      // 处理数据
      // this.payloadData.forEach((item, index) => {
      //   let obj = {
      //     chnVal: '',
      //     key: index
      //   }
      //   obj.chnVal = item.groupName;
      //   this.multipleData.push(obj);
      // })
      // this.radio = this.multipleData[currentIndex].chnVal;

      // 按照图表处理数据
      let seriesData = [];
      if (!this.payloadData.data) {
        return false;
      }
      let valueData = this.payloadData.data.y;
      valueData.forEach(item => {
        let obj = {
          value: '',
          name: ''
        }
        obj.value = item[0].val;
        obj.name = item[0].name;
        seriesData.push(obj);
      })
      this.loading = false;

      this.$nextTick(() => {
        if (valueData.length != 0) {
          this.drawCharts(seriesData);
        }
      })
    },
    drawCharts(seriesData) {
      var datas = [seriesData];
      let myChart = echarts.init(document.getElementById('pieCharts' + this.id));
      //清除残留数据
      myChart.clear()

      let option = {
        tooltip: {
          trigger: 'item',
          formatter: (val) => {
            return `<div style="max-width:200px;word-break: break-all;word-wrap: break-word;white-space:pre-wrap">${val.name} : ${val.value} (${val.percent}%)<div>`
          },
          textStyle: {
            overflow: 'break'
          }
        },

        //图例不显示
        // legend: {
        //   orient: 'vertical',
        //   left: 'left'
        // },
        toolbox: {
          show: true,
        },
        series: datas.map((data, idx) => {
          var top = idx * 33.3;
          return {
            name: this.chartName,
            type: 'pie',
            radius: [70, 114],
            top: top + '%',
            height: '88%',
            left: 'center',
            width: 450,
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1,
            },
            label: {
              alignTo: 'edge',
              formatter: '{name|{b}}\n{time|{c}}',
              minMargin: 5,
              edgeDistance: 10,
              lineHeight: 15,
              fontSize: 14,
              rich: {
                time: {
                  fontSize: 14,
                  color: '#999'
                }
              }
            },
            labelLine: {
              length: 15,
              length2: 0,
              maxSurfaceAngle: 80
            },
            labelLayout: (params) => {
              const isLeft = params.labelRect.x < myChart.getWidth() / 2;
              const points = params.labelLinePoints;
              // Update the end point.
              points[2][0] = isLeft
                ? params.labelRect.x
                : params.labelRect.x + params.labelRect.width;
              return {
                labelLinePoints: points
              };
            },
            data: data
          };
        })
      };
      // {
      //   tooltip: {
      //     trigger: 'item',
      //     formatter: '{a} <br/>{b} : {c} ({d}%)'
      //   },
      //   legend: {
      //     orient: 'vertical',
      //     left: 'left'
      //   },
      //   toolbox: {
      //     show: true,
      //   },
      //   series: [
      //     {
      //       name: this.chartName,
      //       type: 'pie',
      //       radius: [30, 130],
      //       center: ['50%', '50%'],
      //       roseType: 'area',
      //       itemStyle: {
      //         borderRadius: 8
      //       },
      //       data: seriesData
      //     }
      //   ]
      // };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    }
  }
}
</script>

<style lang="scss" scoped>
.pieChart {
  width: 100%;
  height: 100%;

  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }

  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 34px;

    &-div {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .left {
      font-size: 12px;
      color: #6b798e;
    }

    .right {
      margin-left: 18px;
    }

    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  &-echarts {}
}
</style>

<style lang="scss">
.pieChart {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>